package com.example.admin.service.impl;

import com.example.admin.result.ResponseResult;
import com.example.admin.service.ServerSentEventsService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import java.io.IOException;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;

@Service
public class ServerSentEventsServiceImpl implements ServerSentEventsService {

    private static final Map<String, SseEmitter> map = new ConcurrentHashMap<>();

    private static final Logger logger = LoggerFactory.getLogger(ServerSentEventsServiceImpl.class);

    /**
     * 创建指定客户端的连接
     * @return 返回创建的SseEmitter对象
     */
    public SseEmitter createEmitter() {
        SseEmitter sseEmitter = new SseEmitter(0L);
        String uuID = UUID.randomUUID().toString();
        if (!map.containsKey(uuID)) {
            map.put(uuID, sseEmitter);
            logger.info("客户端:[{}]新建连接成功，当前客户端总数为[{}]", uuID, map.size());
        }
        return sseEmitter;
    }

    /**
     * 关闭指定客户端的连接
     * @param clientID 客户端的唯一标识符
     */
    public ResponseResult<Object> close(String clientID) {
        if (map.containsKey(clientID)) {
            map.get(clientID).complete();
            map.remove(clientID);
            logger.info("客户端:[{}]关闭连接成功，当前客户端总数为[{}]", clientID, map.size());
        }
        return ResponseResult.succeed("000000", "关闭连接成功");
    }

    /**
     * 向所有连接的客户端发送消息
     */
    public ResponseResult<Object> send() {
        if (map.size() > 0) {
            String uuID = UUID.randomUUID().toString();
            for (Map.Entry<String, SseEmitter> entry : map.entrySet()) {
                SseEmitter sseEmitter = map.get(entry.getKey());
                try {
                    sseEmitter.send(SseEmitter.event().reconnectTime(1000).id(entry.getKey()).data(uuID));
                    logger.info("客户端:[{}]发送消息成功  消息内容:[{}]", entry.getKey(), uuID);
                } catch (IOException e) {
                    map.remove(entry.getKey());
                }
            }
        }
        return ResponseResult.succeed("000000", "发送消息成功");
    }

}
